import SendMsg from "@/api/SendMsg";
import {message} from "ant-design-vue";

import {validateLength} from "../../../../util/ValidateCateLength";

const VALUE_TYPE_STR = 'STR'
const VALUE_TYPE_INT = 'INT'
const VALUE_TYPE_DOUBLE = 'DOUBLE'



// 参数设定页面的变量
const js3400 = {
    namespaced: true,
    state: {
        VALUE_TYPE_STR,
        VALUE_TYPE_INT,
        VALUE_TYPE_DOUBLE,
        cateData: [],//全表查询数据集
        treeData: [{
            title: "Code",
            key: '0-0',
            slots: {
                icon: 'smile'
            },
            children: []
        }],//树形控件的数据集
        selectData: [],//右边form表单内显示的信息数据集
        codeData: [],//参数各项描述数据集
        selectCateLabel: {},
        selDataSeqId: '',
        selectDataCateDesc: '',
        loadTree: false,
        tempChildren: [],
        paramFormRules: {},
        mainFlgArray: [],
        codeDetails: {},
        cateForm: {
            m_para_type: '',
            m_para_desc: '',
            m_data_id: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_data_ext: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_data_item: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_1: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_2: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_3: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_4: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_5: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_6: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_7: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_8: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_9: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_ext_10: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            m_data_desc: {
                value: '',
                mainFlg: false,
                valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                valueLength: null,
                valueAccuracy: null,
            },
            authFlg: ''
        },
        updateCateForm: {},
        VALUE_NAME: {
            m_data_id: "DATA_ID",
            m_data_ext: "DATA_EXT",
            m_data_item: "DATA_ITEM",
            m_ext_1: "EXT_1",
            m_ext_2: "EXT_2",
            m_ext_3: "EXT_3",
            m_ext_4: "EXT_4",
            m_ext_5: "EXT_5",
            m_ext_6: "EXT_6",
            m_ext_7: "EXT_7",
            m_ext_8: "EXT_8",
            m_ext_9: "EXT_9",
            m_ext_10: "EXT_10",
            m_data_desc: "DATA_DESC"
        },
        cateOldColumns:[],
        treeLoadedKeys: ['0-0'],
        cateDataCnt: 0,
    },
    getters: {
        formDataList: state => paramFormSort(state.selectData.filter(e => e.key != 'dataSeqId')),
        paramData: state => state.cateData.filter(e => e.dataId != 'CATE' && e.dataId != 'CODE')
    },
    mutations: {
        setCateForm(state, val){
            state.cateForm = val
        },
        setTreeLoadedKeys(state, val){
            state.treeLoadedKeys = val
        },
        queryCateDataCnt(state, val){
            SendMsg.getBisData({dataCate: val}, (data) => {
                state.cateDataCnt = data.length
            })
        },
        // 展开类型节点，请求类型下数据
        requestChildrenNode(state, {data, resolve}) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: data.obj.dataId
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if(outTrx.rtnCode !== '0000000'){
                    return
                }
                data.isLeaf = outTrx.oary.length === 0
                data.children = outTrx.oary.map(e => {
                    let title = e.dataDesc;
                    let key = e.dataSeqId;
                    return {
                        obj: e,
                        nodeType: 'data',
                        title: title,
                        key: key,
                        isLeaf: true,
                        scopedSlots: {icon: 'param'}
                    }
                })
                state.treeData = [...state.treeData]
                if (typeof (resolve) === 'function') {
                    resolve();
                }

            });

        },

        requestCode(state, {dataId, dataCate}) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: 'CODE',
                    dataId: dataId
                }]
            };
            state.selectData[0].value = dataCate

            state.selectData = [state.selectData[0]]
            SendMsg.sendPostTrx(codeInTrx).then((res) => {

                if (res.data.rtnCode == "0000000") {
                    let temp = res.data.oary

                    let result = temp.map(e => {
                        let number = e.dataExt.indexOf("_");
                        let s = e.dataExt.replace("_", "").toLowerCase();
                        let ext = s.substring(0, number) + s.charAt(number).toUpperCase() + s.substring(number + 1)
                        return {
                            key: ext,
                            value: '',
                            text: e.dataDesc,
                            requireFlag: true,
                            disableFlag: false,
                            itemSelectFlag: false,
                            dataCateFlag: false,
                            descFlag: false,
                            ext1: e.ext1,
                            ext2: e.ext2,
                            ext3: e.ext3,
                            ext4: e.ext4,
                            ext5: e.ext5,
                            ext6: e.ext6,
                            ext7: e.ext7,
                            ext8: e.ext8,
                            ext9: e.ext9,
                            ext10: e.ext10,
                        }
                    })
                    state.selectData = [...state.selectData, ...result]
                    this.commit('js3400/initRulesAndMainFlgArray')
                }
            });
        },
        updateSelectDataCateDesc(state, val) {
            state.selectDataCateDesc = val
        },
        // 初始化请求所有类型
        queryAllCateInfo(state, treeSearchKey) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: "CATE"
                }]
            };
            state.loadTree = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if ('0000000' === outTrx.rtnCode) {
                    state.cateData = outTrx['oary'].filter(e => e.dataId != null);
                    js3400.mutations.setTreeData(state, treeSearchKey);
                }
            });
            js3400.mutations.initCodeDataQuery(state)
        },
        // 设置属性图类型数据
        setTreeData(state, treeSearchKey) {
            state.treeData[0].children = []
            let tempChildren = []
            state.cateData.forEach(data => {
                if (data['dataCate'] === 'CATE' && data['dataId'] != 'CATE' && data['dataId'] != 'CODE') {
                    let dataId = data['dataId'];
                    let dataSeqId = data['dataSeqId'];
                    tempChildren.push({
                        obj: data,
                        nodeType: 'cate',
                        title: dataId + ' : ' + data.dataDesc,
                        key: dataSeqId,
                        scopedSlots: {icon: 'dataCate'},
                        authFlg: data.authFlg
                    });
                    state.tempChildren = tempChildren
                }
            });
            state.treeData[0].children = tempChildren
            state.treeLoadedKeys = ['0-0']
            state.loadTree = false
            if(treeSearchKey){
                js3400.mutations.searchParamInfo(state, treeSearchKey)
            }
        },
        //参数类型涉及的列查询
        initCodeDataQuery(state) {
            state.codeData = [];
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: "CODE",
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode == '0000000') {
                    state.codeData = outTrx.oary.map(data => {
                        return {
                            ...data
                        };
                    });
                }

            });
        },
        showCodeDetail(state, data) {
            // 类型属性描述信息
            let codeDetails = state.codeData.filter(e => e.dataId === data.dataId);
            state.selectCateLabel = {}
            let a = {}
            codeDetails.forEach(e => {
                a[e.dataExt] = e.dataDesc
            })
            state.selectCateLabel = {...a, label: data.dataId}
            state.selectData = []
            state.selectData.push({
                dataCateFlag: true,
                text: 'DATA_CATE',
                key: data.dataId,
                value: data.dataId,
                disableFlag: true,
            })

            let temp = codeDetails.map(e => {
                return {
                    dataCateFlag: true,
                    text: e.dataExt,
                    key: e.dataDesc,
                    value: e.dataDesc,
                    disableFlag: true,
                }
            })
            state.selectData = paramFormSort([...state.selectData, ...temp], true)
        },
        getColName(state, code) {
            let codeDetails = state.codeData.filter(e => e.dataId == code);
            state.selectCateLabel = {}
            let a = {}
            codeDetails.forEach(e => {
                a[e.dataExt] = e.dataDesc
            })
            state.selectCateLabel = {...a, label: code}
            state.codeDetails = codeDetails
        },
        dataItemQuery(state, payload) {
            let code = payload.node.dataRef.obj.dataCate;
            // if (state. Object.keys(state.selectCateLabel).length == 0 || state.selectCateLabel.label != code || !state.codeDetails) {

                js3400.mutations.getColName(state, code)
            // }
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataSeqId: payload.selectedKey,
                    dataCate: payload.node.dataRef.obj.dataCate
                }]
            };
            let findIndex = state.cateData.findIndex(e => e.dataId == code)
            state.selectDataCateDesc = state.cateData[findIndex].dataDesc
            state.selectData = []
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                let obj = outTrx['oary'];
                let element = obj[0];
                let requireFlag = false;
                let disableFlag = true;
                let itemSelectFlag = false;
                let dataCateFlag = false;
                let descFlag = false;
                if (element) {
                    Object.keys(element).map(key => {
                        if (key == 'dataSeqId') {
                            state.selDataSeqId = element[key]
                            state.selectData.push({
                                key: key,
                                value: element[key],
                            });
                            return
                        }
                        if (key == 'dataCate') {
                            state.selectData.push({
                                key: key,
                                value: element[key],
                                text: 'Permission Type:',
                                requireFlag: false,
                                disableFlag: true,
                                itemSelectFlag: false,
                                dataCateFlag: true,
                                descFlag: true,
                            });
                            return;
                        }

                        let text = key.replace(/([A-Z]|[0-9]+)/g, "_$1").toUpperCase();

                        if (state.selectCateLabel[text]) {
                            let objIndex = state.codeDetails.findIndex( e => e.dataExt === text)
                            if(objIndex !== -1){
                                let obj = state.codeDetails.splice(objIndex, 1)[0]
                                state.selectData.push({
                                    key: key,
                                    value: element[key],
                                    text: state.selectCateLabel[text],
                                    requireFlag: requireFlag,
                                    disableFlag: disableFlag,
                                    itemSelectFlag: itemSelectFlag,
                                    dataCateFlag: dataCateFlag,
                                    descFlag: descFlag,
                                    ext1: obj.ext1,
                                    ext2: obj.ext2,
                                    ext3: obj.ext3,
                                    ext4: obj.ext4,
                                    ext5: obj.ext5,
                                    ext6: obj.ext6,
                                    ext7: obj.ext7,
                                    ext8: obj.ext8,
                                    ext9: obj.ext9,
                                    ext10: obj.ext10,
                                })
                            }
                        }

                    });
                    // 值不存在时渲染空白值
                    state.codeDetails.forEach( e => {
                        if (state.selectCateLabel[e.dataExt]) {
                            let key = e.dataExt.toLowerCase().replace(/_(\w)/, (all, p1) => {
                                return p1.toUpperCase()
                            })
                            state.selectData.push({
                                key: key,
                                value: '',
                                text: state.selectCateLabel[e.dataExt],
                                requireFlag: requireFlag,
                                disableFlag: disableFlag,
                                itemSelectFlag: itemSelectFlag,
                                dataCateFlag: dataCateFlag,
                                descFlag: descFlag,
                                ext1: e.ext1,
                                ext2: e.ext2,
                                ext3: e.ext3,
                                ext4: e.ext4,
                                ext5: e.ext5,
                                ext6: e.ext6,
                                ext7: e.ext7,
                                ext8: e.ext8,
                                ext9: e.ext9,
                                ext10: e.ext10,
                            })
                        }
                    })
                    this.commit('js3400/initRulesAndMainFlgArray')
                    if (typeof (payload.callback) === 'function') {
                        payload.callback();
                    }
                }
            });
        },

        //新增和修改参数时，生成rule以及mainFlgArray
        initRulesAndMainFlgArray(state){
            state.paramFormRules = {}
            state.selectData.forEach(item => {
                // 设置dataDesc始终为必填
                if(item.key ==="dataDesc"){
                    item.ext1 = 'true'
                }
                switch (item.ext2) {
                    case VALUE_TYPE_STR:
                        state.paramFormRules[item.key] = [
                            {required: item.ext1 === 'true', message: `Please Input[${item.text}]`, trigger: 'blur'},
                            {validator: (rule, value, callback) => validateLength(value, callback, item.key, item.ext3), trigger: 'blur'},
                        ]
                        break;
                    case VALUE_TYPE_INT:
                        state.paramFormRules[item.key] = [
                            {required: item.ext1 === 'true', message: `Please Input[${item.text}]，值为整数`, trigger: 'blur'},
                            {validator: (rule, value, callback) => validateLength(value, callback, item.key, Infinity), trigger: 'blur'},
                        ]
                        break;
                    case VALUE_TYPE_DOUBLE:
                        state.paramFormRules[item.key] = [
                            {required: item.ext1 === 'true', message: `Please Input[${item.text}]，小数点后保留${item.ext5}位`, trigger: 'blur'},
                            {validator: (rule, value, callback) => validateLength(value, callback, item.key, Infinity), trigger: 'blur'},
                        ]
                        break;
                    default:
                }
            })
            state.mainFlgArray = state.selectData.filter( k => k.ext1 === 'true').map( e => e.key)
        },

        initAddParamForm(state) {
            state.selectData = []
            state.selectData.push({
                key: 'dataCate',
                value: '',
                text: 'Parameter Type',
                requireFlag: true,
                disableFlag: false,
                itemSelectFlag: true,
                dataCateFlag: true,
                descFlag: '参数类型选择',
            })
            state.selectDataCateDesc = ''

        },

        //参数类型新增
        addCateData(state, {data, callback, updateType}) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: updateType ? "R" : "N",
                iary: [...data]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode === '0000000') {
                    if(updateType){
                        message.success('Successfully modified')
                    }else{
                        message.success('Successfully added')
                    }

                    if (typeof (callback) === 'function') {
                        callback();
                    }
                }

            });
        },
        //参数类型删除
        removeCateData(state, {dataCate, callback}) {

            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "C",
                iary: [{
                    dataCate: dataCate
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode == '0000000') {
                    message.info('Successfully deleted')
                    let index = state.cateData.findIndex(data => dataCate === data.dataId);
                    state.cateData.splice(index, 1);
                    if (typeof (callback) === 'function') {
                        callback();
                    }
                    let cateIndex = state.treeData[0].children.findIndex(e => e.obj.dataId == dataCate)
                    state.treeData[0].children.splice(cateIndex, 1)
                }
            });
        },
        //treeData增加参数数据
        addTreeData(state, payload) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "A",
                iary: [{...payload.params}]
            };
            let flg = true
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode != '0000000') {
                    flg = false
                    return
                }
                message.info(payload.successPrompt)
                this.commit('js3400/refreshCateData', {dataId: payload.params.dataCate})

                state.selectData.forEach(e => {
                    e.disableFlag = true
                })

            }).finally(() => {
                if (typeof (payload.callback) === 'function') {
                    payload.callback(flg);
                }
            })
        },
        //添加参数后更新参数类型节点
        refreshCateData(state, {dataId}) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "Q",
                iary: [{
                    dataCate: dataId
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode === "0000000") {
                    let parIndex = state.treeData[0].children.findIndex(e => e.obj.dataId === dataId && e.children)
                    if (parIndex !== -1) {
                        state.treeData[0].children[parIndex].isLeaf = outTrx.oary.length === 0
                        state.treeData[0].children[parIndex].children = outTrx.oary.map(e => {
                            let title = e.dataDesc;
                            let key = e.dataSeqId;
                            return {
                                obj: e,
                                nodeType: 'data',
                                title: title,
                                key: key,
                                isLeaf: true,
                                scopedSlots: {icon: 'param'}
                            }
                        })
                        state.treeData = [...state.treeData]
                    }
                }
            })
        },
        //treeData修改参数数据
        updateTreeData(state, payload) {

            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "U",
                iary: [{...payload.params}]
            };
           // console.log(payload)
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                if (res.data.rtnCode != '0000000') {
                    return
                }

                message.info(payload.successPrompt)

                let parIndex = state.treeData[0].children.findIndex(e => e.obj.dataId == payload.params.dataCate && e.children)
                if (parIndex != -1) {
                    let index = state.treeData[0].children[parIndex].children.findIndex(c => c.key == payload.params.dataSeqId)
                    let item = {...state.treeData[0].children[parIndex].children[index]}
                    state.treeData[0].children[parIndex].children[index] = {
                        obj: {...item.obj, ...payload.params},
                        nodeType: 'data',
                        title: payload.params.dataDesc,
                        key: payload.params.dataSeqId,
                        isLeaf: true,
                        scopedSlots: {icon: 'param'}
                    }
                    state.treeData = [...state.treeData]
                }

                state.selectData.forEach(e => {
                    e.disableFlag = true
                })
                payload.hideSaveButton();
            }).finally(() => {
                if (typeof (payload.endLoading) === 'function') {
                    payload.endLoading();
                }
            })
        },
        //treeData删除参数数据
        removeTreeData(state, {dataCate, dataSeqId, resolve}) {
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "D",
                iary: [{
                    dataSeqId: dataSeqId
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then((res) => {
                let outTrx = res.data;
                if (outTrx.rtnCode == '0000000') {
                    message.info('Successfully deleted')
                    state.loadTree = false
                    let parIndex = state.treeData[0].children.findIndex(e => e.obj.dataId == dataCate && e.children)
                    if (parIndex != -1) {
                        let index = state.treeData[0].children[parIndex].children.findIndex(c => c.key == dataSeqId)
                        state.treeData[0].children[parIndex].children.splice(index, 1)

                        state.treeData[0].children[parIndex].isLeaf = state.treeData[0].children[parIndex].children.length === 0

                        state.treeData = [...state.treeData]
                    }

                }
                if (typeof (resolve) === 'function') {
                    resolve()
                }
            });
        },
        //form表单修改数据
        udpateFormData(state, payload) {
            let obj = state.selectData[payload.id];
            obj[payload.key] = payload.value;
            state.selectData.splice(payload.id, 1, obj);
        },
        //清除form表单数据
        cleanFormData(state) {
            state.selectData = [];
        },
        //树本地搜索
        searchParamInfo(state, val) {
            let cr = val
            if (!cr) {
                state.treeData[0].children = [...state.tempChildren]
                return
            }
            let filter = state.tempChildren.filter((e) => e.title.indexOf(cr) > -1);
            state.treeData[0].children = filter
        },
        //修改类型时，获取类型的信息
        updateTypeFunc(state, dataId){
            let codeInTrx = {
                trxId: "bisData",
                actionFlg: "QD",
                iary: [{
                    dataId: dataId,
                }]
            };
            SendMsg.sendPostTrx(codeInTrx).then(({data}) => {
                if (data.rtnCode !== '0000000') {
                   return
                }
                let cate = data.oary.find( e => e.dataCate === 'CATE')
                if(!cate){
                    message.warn("参数类型不存在")
                    return
                }
               // console.log(cate)
                let formData = {
                    m_para_type: cate.dataId,
                    m_para_desc: cate.dataDesc,
                    authFlg: cate.authFlg
                }
                state.cateOldColumns = []
                Object.keys(state.VALUE_NAME).forEach( key =>{
                    let obj = data.oary.find(e => e.dataExt === state.VALUE_NAME[key])
                    if(obj){
                        formData[key] = {
                                dataSeqId: obj.dataSeqId,
                                value: obj.dataDesc,
                                mainFlg: obj.ext1 === 'true',
                                valueType: obj.ext2,
                                valueMax: (obj.ext2 !== VALUE_TYPE_INT && obj.ext2 !== VALUE_TYPE_DOUBLE)  ? null : obj.ext3,
                                valueMin: obj.ext4,
                                valueLength: obj.ext2 !== VALUE_TYPE_STR ? null : obj.ext3,
                                valueAccuracy: obj.ext5,
                        }
                        state.cateOldColumns.push(
                                obj.dataExt
                        )

                    }else{
                        formData[key] = {
                            value: '',
                            mainFlg: false,
                            valueType: VALUE_TYPE_STR, valueMax: null, valueMin: null,
                            valueLength: null,
                            valueAccuracy: null,
                        }
                    }
                })
                state.cateForm = formData
            });
        }

    },
    action: {

    }
}

function paramFormSort(val, flg) {
    let sortArr = ['dataCate','dataDesc','dataId','dataExt','dataItem','ext1','ext2','ext3','ext4','ext5','ext6','ext7','ext8','ext9','ext10']
    val.forEach(item => {
        let index = sortArr.findIndex(key => {
            if(flg){
                key = key.replace(/([A-Z]|[0-9]+)/g, "_$1").toUpperCase();
                return item.text === key
            }
            return item.key === key
        })
        if(index !== -1){
            item.sortIndex = index
        }
    })
    val.sort((a,b) => a.sortIndex - b.sortIndex).forEach( e => delete e.sortIndex)
    return val
}

export default js3400;
